/**
 * 系统设置 处方
 */
<template>
  <div>
  <el-row>
      <el-col :span="24">
        <h3>患者信息</h3>
      </el-col>
    </el-row>
      <el-row :gutter="10">
        <el-col :span="24">
          <div class="grid-content bg-purple">
                <!-- 患者信息 -->
                <el-form :inline="true" :model="formInline" class="user-search">
                  <el-form-item label="患者姓名">
                    <el-input :disabled="true" size="small" v-model="formInline.name" ></el-input>
                  </el-form-item>
                  <el-form-item label="患者年龄">
                    <el-input :disabled="true" size="small" v-model="formInline.age" ></el-input>
                  </el-form-item>
                  <el-form-item label="患者性别">
                    <el-input :disabled="true" size="small" v-model="formInline.sex" ></el-input>
                  </el-form-item>
                </el-form>
          </div>
        </el-col>
      </el-row>
          <el-row>
      <el-col :span="24">
        <h3>处方信息</h3>
      </el-col>
    </el-row>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="24" :lg="15" :xl="15">
          <div class="grid-content bg-purple-light">
              <el-form :inline="true" :model="formInline" class="user-search">
                  <el-form-item label="处方类型">
                    <el-select size="small" v-model="prescriptionType " placeholder="选择处方类型">                     
                      <el-option label="西/成药处方" value="西/成药处方"></el-option>
                      <el-option label="中药处方" value="中药处方"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="科室">
                    <el-input :disabled="true" size="small" v-model="formInline.office" ></el-input>
                  </el-form-item>
                  <el-form-item label="接诊医生">
                    <el-input :disabled="true" size="small" v-model="formInline.doctorName" ></el-input>
                  </el-form-item>
                  <el-form-item label="处方总价">
                    <el-input :disabled="true" size="small" v-model="formInline.totalPrice" >
                    </el-input>
                  </el-form-item>
                </el-form>
            <el-table size="small" :data="selectedMedicine" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%">
              <el-table-column prop="commonName" label="药品名称" width="150">
              </el-table-column>
              <el-table-column prop="usage"  label="用法" width="120">
                <template slot-scope="scope">
                  <el-select size="small" v-model="scope.row.usage">                     
                    <el-option 
                    v-for="(label, value) in drugDict.usage"
                    :key="value"
                    :label="label"
                    :value="label"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="dosage" label="单次用量" width="80">
                <template slot-scope="scope">
                <el-select v-model="scope.row.dosage" size="small">                     
                    <el-option
                    v-for="item in 30"
                    :key="item"
                    :label="item"
                    :value="item"></el-option>
                    
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column  prop="quantity" label="总数量" width="80">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.quantity" size="small" @change="calculatePrice">                     
                    <el-option
                    v-for="item in 30"
                    :key="item"
                    :label="item"
                    :value="item"></el-option>
                  </el-select>     
                </template>
              </el-table-column>
              <el-table-column prop="dosageUnit"  label="用量单位" width="80">
                <template slot-scope="scope">
                  <el-select size="small" v-model="scope.row.dosageUnit" >                     
                    <el-option 
                    v-for="(label, value) in drugDict.unit"
                    :key="value"
                    :label="label"
                    :value="label">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="frequency"  label="用药频率" width="140">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.frequency" size="small" >                     
                    <el-option 
                    v-for="(label, value) in drugDict.frequency"
                    :key="value"
                    :label="label"
                    :value="label">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="medicineDays"  label="用药时间(天)" width="100">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.medicineDays" size="small">                     
                    <el-option
                    v-for="item in 30"
                    :key="item"
                    :label="item"
                    :value="item"></el-option>
                    
                  </el-select>   
                </template>
              </el-table-column>
              
              <el-table-column  prop="price" label="单价(元)" width="80">
                <template slot-scope="scope">
                  <div>{{ scope.row.price / 100 }}</div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" min-width="50">
                <template slot-scope="scope">
                  <el-button size="mini" type="danger" @click="unSelectMedicine(scope.$index, scope.row)" >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <br/>
            <el-button type="primary" round @click="savePrescription">开具处方</el-button>
            <el-button type="danger" round @click="chargePrescription">开具处方并收费</el-button>

          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :md="24" :lg="9" :xl="9">
          <div class="grid-content bg-purple">
            <!-- 搜索筛选 -->
            <el-form :inline="true" :model="searchForm" class="user-search">
              <el-form-item label="药品类型：">
                <!-- 可清空下拉框 -->
                <el-select size="small" style="width:100px" clearable  v-model="searchForm.drugClassId">
                  <!--根据字典表生成下拉选项-->
                  <el-option v-for="(label, value) in drugDict.class" :key="value" :label="label" :value="Number(value)" ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="关键字：">
                <el-input  size="small"  v-model="searchForm.keyword" placeholder="输入药品名称/药品编码/拼音" ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
              </el-form-item>
            </el-form>
            <!--列表-->
            <el-table size="small" :data="listData" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%">
              <el-table-column sortable prop="commonName" label="药品名称" width="160">
              </el-table-column>
              <el-table-column sortable prop="norm" label="规格" width="90">
                <template slot-scope="scope">
                  <div>
                    {{ scope.row.doseFactor }}{{ drugDict.unit[scope.row.doseUnit] }}*{{scope.row.basicFactor}}{{ drugDict.unit[scope.row.basicUnit] }}/{{ drugDict.unit[scope.row.unitId]}}
                  </div>
                </template>
              </el-table-column>
              <el-table-column sortable prop="waterMark" label="库存" width="60">
              </el-table-column>
              <el-table-column sortable prop="price" label="单价" width="60">
                <template slot-scope="scope">
                  <div>{{ scope.row.price / 100 }}</div>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" min-width="50">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary" @click="selectMedicine(scope.$index, scope.row)" >选择</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>

      <!-- 处方开立支付弹窗 -->
    <el-dialog title="处方开立费用支付" :visible.sync="detailVisable" width="621px" @click="closeDialog">
      <el-container>
      <el-main>
      <el-table size="small" :data="selectedMedicine" highlight-current-row v-loading="loading" border element-loading-text="拼命加载中" style="width: 100%;">      
      
      <el-table-column sortable prop="quantity" label="药品数量" width="100">
      </el-table-column>

      <el-table-column sortable prop="commonName" label="药品名称" width="160">
      </el-table-column>
      <el-table-column sortable prop="price" label="单价" min-width="80">
        <template slot-scope="scope">
                <div>{{scope.row.price/100}}</div>
              </template>
      </el-table-column>

      </el-table>  
      </el-main>
      <el-footer>
        <div >
          应收处方开立费用：{{totalPrice}}元
        </div>
      </el-footer> 
      </el-container>
      <template>
          <el-button size="small" @click="closeDialog">取消</el-button>
          <el-button size="mini" type="danger" @click="updatePrChargeStatus()">确认交费</el-button>
      </template>
    </el-dialog>


  </div>
</template>

<script>
// 引入药品类型字典
import { drugDict } from "../../dict/drugDict";
// 引入 Axios
import axios from "axios";

export default {
  data() {
    return {
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      detailVisable:false,
      totalPrice:0,
      title: "添加",
      editMedicine: {},
      // 搜索框数据
      searchForm: {
        keyword: "",
        drugClassId: null
      },
      userparm: [], //搜索权限
      listData: [], //用户数据
      drugDict: drugDict, // 药品相关字典
      // 已经选择的药物
      selectedMedicine: [], 
      // 处方类型
      prescriptionType:'',
      // 患者信息
      formInline:{
        name:'',
        age:'',
        sex:'',
        office:'  ',
        doctorName:'',
        totalPrice:0
      }
    };
  },
  // 注册组件
  components: {
    
  },
  created() {
    this.getdata();
    this.showPatientInfo();
    
  },
  methods: {
    // 获取患者信息
    showPatientInfo(){
      this.formInline.name=this.$route.query.patientName;
      this.formInline.age=this.$route.query.patientAge;
      this.formInline.sex=this.$route.query.patientSex;
      this.formInline.office=this.$route.query.office;
      this.formInline.doctorName=this.$route.query.doctorName;
     
    },

    // 计算价格
    calculatePrice(){

      
      this.formInline.totalPrice=0;
      for(let i=0;i<this.selectedMedicine.length;i++){


        (this.formInline.totalPrice)+=(this.selectedMedicine[i].quantity)*(this.selectedMedicine[i].price)
        
      }
      this.formInline.totalPrice=(this.formInline.totalPrice)/100;

    },

    // 获取数据
    getdata() {
      this.loading = true;
      // 待提交的数据
      let dto = {
        pageNum: 1,
        pageSize: 100000000,
      };
      // 根据 this.searchForm 进行构建 dto
      if (this.searchForm.keyword !== "")
        dto.keywords = this.searchForm.keyword;
      if (this.searchForm.drugClassId !== null) {
        if (dto.medicine === undefined) dto.medicine = {};
        dto.medicine.classId = this.searchForm.drugClassId;
      }
      // 发送请求
      axios
        .post("/api/medicine/select", dto)
        .then((res) => {
          if (res.data.data == null) {
            throw "error";
          }
          return res.data.data;
        })
        .then((data) => {
          this.listData = data.list;
        })
        .catch((err) => {
          this.loading = false;
          this.$message.error("获取数据失败，请稍后再试！");
        });
      this.loading = false;
    },
    // 搜索事件
    search() {
      this.getdata();
    },
    // 选药
    selectMedicine(index,row){
      
      let hasMedicine=false;
      for(let i=0;i<this.selectedMedicine.length;i++){
        if(this.selectedMedicine[i].medicineId==row.id){
          this.selectedMedicine[i].quantity+=1;
          hasMedicine=true;
          break;
        }
      }
      if(hasMedicine==false){
        this.selectedMedicine
            .push({
              
              "medicineId": row.id,
              "commonName": row.commonName,
              "price": row.price,
              "quantity":1,
              "usage":"",
              "dosage":"",
              "dosageUnit":"",
              "frequency":"",
              "medicineDays":2
            });
      }

      this.calculatePrice();

    },
    unSelectMedicine(index,row){
      this.selectedMedicine.splice(index,1);

      this.calculatePrice();
    },
    savePrescription(){

      console.log("selected---",this.selectedMedicine);
      axios.post('/api/prescription/insert',{
        registerId: this.$route.query.registerId,
        prescriptionType: this.prescriptionType,
        chargeStatus:0,
        prescriptionItemList: this.selectedMedicine
      })
      .then(res => {

        console.log('更新的结果是',res)
        if (res.data.code==200) {
          
          this.$message({
            type: 'success',
            message: '处方保存成功！'
          })


          
                this.$router.push({
                  path:"/workbench/patientInfo",
                  query:{
                    patientId: this.$route.query.patientId,
                    registerId: this.$route.query.registerId,
                    patientName:this.$route.query.patientName,
                    patientAge:this.$route.query.patientAge,
                    patientSex:this.$route.query.patientSex,
                    }
                })
        } else {
          this.$message({
            type: 'info',
            message: res.data.message
          })
        }
      })
      .catch(err => {
        this.editFormVisible = false
        this.loading = false
        this.$message.error('处方保存失败，请稍后再试！')
      })
    },

    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisible = false
      this.detailVisable = false
    },


    //展示处方开立交费弹框
    chargePrescription(){
      this.totalPrice=this.formInline.totalPrice
        
        this.detailVisable = true
        
    },

    updatePrChargeStatus(){
      this.detailVisable = false
      axios.post('/api/prescription/insert',{
        registerId: this.$route.query.registerId,
        prescriptionType: this.prescriptionType,
        chargeStatus:1,
        prescriptionItemList: this.selectedMedicine
      })
      .then(res => {

        console.log('更新的结果是',res)
        if (res.data.code==200) {
          
          this.$message({
            type: 'success',
            message: '处方保存成功！'
          })

           axios.post('/api/register/updateCase',{
          "id":this.$route.query.registerId,

          "treatmentStatus":"已完成"
        })
        .then(res => {
              
              if (res.data.code==200) {
                
                this.$message({
                  type: 'success',
                  message: '已完成！'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: res.data.message
                })
              }
            })
            .catch(err => {
              this.editFormVisible = false
              this.loading = false
              this.$message.error('更新接诊状态失败，请稍后再试！')
            })


          
                this.$router.push({
                  path:"/workbench/patientInfo",
                  query:{
                    patientId: this.$route.query.patientId,
                    registerId: this.$route.query.registerId,
                    patientName:this.$route.query.patientName,
                    patientAge:this.$route.query.patientAge,
                    patientSex:this.$route.query.patientSex,
                    }
                })
        } else {
          this.$message({
            type: 'info',
            message: res.data.message
          })
        }
      })
      .catch(err => {
        this.editFormVisible = false
        this.loading = false
        this.$message.error('处方保存失败，请稍后再试！')
      })

      

    }
  }
}
</script>

<style scoped>
  .hr {
    border-style: dashed;
    color: gainsboro;
  }
  .edit-input {
    width: 75%;
  }
  .user-search {
    margin-top: 20px;
  }
  .userRole {
    width: 100%;
  }
  .el-col {
    border-radius: 4px;
  }


  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
</style>